package com.yinhe.music.yhmusic.pay;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BasePresneterActivity;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.model.PayResultInfo;
import com.yinhe.music.yhmusic.personal.model.PayResult;
import com.yinhe.music.yhmusic.personal.model.ResultInfo;
import com.yinhe.music.yhmusic.utils.ViewUtils;
import com.yinhe.music.yhmusic.widget.SmoothCheckBox;

import java.util.Map;

public class PayActivity extends BasePresneterActivity implements PayContract.IPayView {
    private SmoothCheckBox checkBox_wechat, checkBox_alipay;
    private LinearLayout ll_wechat, ll_alipay;
    private TextView text_money;
    private String money;
    private boolean isSelect_alipay = false, isSelect_wechat = true;
    private IWXAPI api;
    private Button payBtn;
    private static final int SDK_PAY_FLAG = 1;
    private String productsType, products;
    private Gson gson = new Gson();
    private ProgressDialog progressDialog;

    PayPresenter mPresenter;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    // 同步返回需要验证的信息
                    String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    if (resultInfo != null) {
                        if (TextUtils.equals(resultStatus, "9000")) {
                            ResultInfo info = gson.fromJson(resultInfo, ResultInfo.class);
                            LogUtils.d(info);
                            mPresenter.getPayResult(info.getAlipay_trade_app_pay_response().getOut_trade_no());
                        } else {
                            // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                            Toast.makeText(PayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(PayActivity.this, "取消支付", Toast.LENGTH_SHORT).show();
                    }
                    payBtn.setEnabled(true);
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    public BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void initPresenter() {
        mPresenter = new PayPresenter();
        mPresenter.attachModelView(new BaseModel(), this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //沙箱环境
//      EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        RxBus.get().register(this);

        checkBox_wechat = findViewById(R.id.checkbox_wechat);
        checkBox_alipay = findViewById(R.id.checkbox_alipay);
        ll_alipay = findViewById(R.id.alipat_layout);
        ll_wechat = findViewById(R.id.wechat_layout);
        payBtn = findViewById(R.id.pay_btn);
        text_money = findViewById(R.id.text_money);

        checkBox_wechat.setChecked(true);
        checkBox_alipay.setChecked(false);
        checkBox_wechat.setClickable(false);
        checkBox_alipay.setClickable(false);

        progressDialog = ViewUtils.showWaitingDialog(this, null, null, false);

        if (getIntent() != null) {
            money = getIntent().getStringExtra("price");
            productsType = getIntent().getStringExtra("productstype");
            products = getIntent().getStringExtra("products");
        }
        text_money.setText("¥" + money);
        setToolbar("支付订单");
        showQuickControl(true);
        regToWx();

        setListener();
    }

    @Override
    protected void onDestroy() {
        RxBus.get().unregister(this);
        super.onDestroy();
    }

    private void regToWx() {
        api = WXAPIFactory.createWXAPI(this, IConstants.APP_ID, true);
        api.registerApp(IConstants.APP_ID);
    }

    private void setListener() {
        checkBox_wechat.setOnCheckedChangeListener((checkBox, isChecked) -> isSelect_wechat = isChecked);

        checkBox_alipay.setOnCheckedChangeListener((checkBox, isChecked) -> isSelect_alipay = isChecked);

        ll_alipay.setOnClickListener(view -> {
            isSelect_alipay = true;
            isSelect_wechat = false;
            checkBox_alipay.setChecked(isSelect_alipay);
            checkBox_wechat.setChecked(isSelect_wechat);
        });

        ll_wechat.setOnClickListener(view -> {
            isSelect_wechat = true;
            isSelect_alipay = false;
            checkBox_wechat.setChecked(isSelect_wechat);
            checkBox_alipay.setChecked(isSelect_alipay);
        });

        payBtn.setOnClickListener(view -> {
            progressDialog.show();
            payBtn.setEnabled(false);
            if (isSelect_wechat) {
                mPresenter.getPayInfo(IConstants.WXPAY, productsType, products);
            } else if (isSelect_alipay) {
                mPresenter.getPayInfo(IConstants.ALIPAY, productsType, products);
            }
        });
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Pay.PAY_STATUS)
    )
    public void onRxbusPayStatus(Integer payStatus) {
        if (payStatus == 1) {
            finish();
        }
    }

    @Override
    public void showMessage(Throwable throwable) {
        super.showMessage(throwable);
        progressDialog.dismiss();
    }

    @Override
    public void sendWechatPay(PayReq payReq) {
        LogUtils.d(payReq);
        api.sendReq(payReq);
        payBtn.setEnabled(true);
        progressDialog.dismiss();
    }

    @Override
    public void sendAliPay(String orderInfo) {
        Runnable payRunnable = () -> {
            PayTask payTask = new PayTask(PayActivity.this);
            Map<String, String> result = payTask.payV2(orderInfo, true);
            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
        progressDialog.dismiss();
    }

    @Override
    public void setPayResultUI(PayResultInfo resultInfo) {
        int payStatus;
        if (resultInfo.isPaySuccess()) {
            payStatus = 1;
            Toast.makeText(PayActivity.this, R.string.pay_success_tip, Toast.LENGTH_SHORT).show();
        } else {
            payStatus = 0;
        }
        RxBus.get().post(RxBusEventType.Pay.PAY_STATUS,(Integer) payStatus);
    }
}
